<?php
/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/7/10 0010
 * Time: 17:12
 */

namespace App\FreeBird\Models;

use App\Admin\Contracts\MemberLevelInterface;
use App\Base\Models\BaseModel;
use App\FreeBird\Contracts\InfoClassInterface;
use App\FreeBird\Contracts\RebateLogInterface;
use App\FreeBird\Exceptions\FreeBirdException;
use App\Weixin\Contracts\UserInterface;
use App\Weixin\Models\WeixinUserIsvipModel;
use App\Weixin\Models\WeixinUserModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

/**
 * 用户支付vip列表
 * Class UserVipPayModel
 * @package App\FreeBird\Models
 */
class UserVipPayModel extends BaseModel
{
    use SoftDeletes;
    /**
     * 表名
     * @var string
     */
    public $table = "freebird_uservip_pay";
    /**
     * 时间自动
     * @var bool
     */
    public $timestamps = true;
    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'create_time';  //修改添加时间字段
    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'update_time';

    /**
     * 删除
     */
    const DELETED_AT = 'delete_time';
    /**
     * 模型的日期字段保存格式。
     */
    protected $dateFormat = 'U';


    /**
     * 用户vip模型
     * @return WeixinUserIsvipModel
     */
    public function getWeixinUserIsvipModel()
    {
        return app()->make(WeixinUserIsvipModel::class);
    }

    /**
     * 获取vipShop模型
     * @return VipShopModel
     */
    public function getVipShopModel()
    {
        return app()->make(VipShopModel::class);
    }

    /**
     * 权限层级
     * @return MemberLevelInterface
     */
    public function getMemberLevelInterface()
    {
        return app(MemberLevelInterface::class);
    }

    /**
     * 用户表
     * @return WeixinUserModel
     */
    public function getWeixinUserModel()
    {
        return app(WeixinUserModel::class);
    }

    /**
     * 返佣日志表
     * @return RebateLogInterface
     */
    public function getRebateLogInterface(){
        return app()->make(RebateLogInterface::class);
    }


    /**
     * 用户接口操作
     * @return UserInterface
     */
    public function getUserInterface(){
        return app()->make(UserInterface::class);
    }
    /**
     * 用户微信支付返回通知购买vip
     * @param  uid  month  pay_id;
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function buyVipUserData($info)
    {
        //获取数据
        $shopInfo = $this->getVipShopModel()->newQuery()->where("id", $info->pay_id)->first();
        $month = $shopInfo->month;
        //判断用户是否已存在vip如果存在则续费上
        $time = time();
        $userVipInfo = $this->getWeixinUserIsvipModel()->newQuery()->where("uid", $info->uid)->where("start_time", "<=", $time)->where("end_time", ">=", $time)->first();  //用户是否已是Vip如果是则加上vip
        $data = array();  //将用户月份到vip中去
        $data["uid"] = $info->uid;
        if (!empty($userVipInfo)) {
            $data["id"] = $userVipInfo->id;
            $endTime = $userVipInfo->end_time; //结束时间
            $endTime = strtotime("+" . $month . " month", $endTime);
            $data["end_time"] = $endTime;
        } else {
            $data["id"] = null;
            $data["start_time"] = $time;
            $data["end_time"] = strtotime("+" . $month . " month", $time);
        }
        $userInfo = $this->getWeixinUserModel()->newQuery()->where("uid", $info->uid)->first();

        $data["lid"] = $userInfo->lid;  //用户等级
        //直推返佣计算
        if (!empty($userInfo->p1)) {  //直推计算
            $p1Data = array();
            $p1Data["order_sn"] = $info->pay_sn;
            $p1Data["uid"] = $info->uid;
            $p1Data['mount_type']=1;
            $p1Data["all_mount"] =$shopInfo->amount;
            $bMount=$shopInfo->amount*get_config_param_value("TS_PUSH_DIECT_BACK")/100;
            $p1Data["b_mount"] =number_format($bMount,2) ;
            $p1Data["source_type"] = 1;
            $p1Data["buid"] = $userInfo->p1;
            $p1Data['type'] = 1;
            if(!empty($bMount)){
              $this->getRebateLogInterface()->saveVipData($p1Data);
            }
        }
        //间推返佣计算
        if (!empty($userInfo->p2)) {
            $p1Data = array();
            $p1Data["order_sn"] = $info->pay_sn;
            $p1Data["uid"] = $info->uid;
            $p1Data['mount_type']=1;
            $p1Data["all_mount"] =$shopInfo->amount;
            $bMount=$shopInfo->amount*get_config_param_value("TS_PUSH_PART_BACK")/100;
            $p1Data["b_mount"] =number_format($bMount,2) ;
            $p1Data["source_type"] = 2;
            $p1Data["buid"] = $userInfo->p2;
            $p1Data['type'] = 1;
            if(!empty($bMount)){
                $this->getRebateLogInterface()->saveVipData($p1Data);
            }
        }
        //权限层级的记录。。。。统计..vip统计次数与总金额
        $udata = array();
        $udata["vip_pay_times"] = DB::raw("vip_pay_times+1");
        $udata["vip_pay_amount"] = DB::raw("vip_pay_amount+" . $shopInfo->amount);
        $this->getMemberLevelInterface()->updateData(["id" => $data["lid"]], $udata);
        if ($this->getWeixinUserIsvipModel()->newQuery()->updateOrCreate(["id" => $data["id"]], $data)) {
            return $this->newQuery()->where("id", $info->id)->update(["order_status" => '20']);  //更新支付状态
        }
    }

    /**
     * 用户金币消费
     * @param $data
     */
    public function buyVipUserScoreData($data){
        $shopInfo = $this->getVipShopModel()->newQuery()->where("id",$data['pay_id'])->first();  //购买商品
        $userInfo = $this->getWeixinUserModel()->newQuery()->where("uid", $data['uid'])->first();  //获取用户
        if($userInfo->score<$shopInfo->amount){
            throw  new FreeBirdException(FreeBirdException::EROOR_VIP_USER_SCORE_ERROR);
        }
        $month = $shopInfo->month;
        //判断用户是否已存在vip..用户成为vip.......如果存在则续费上
        $time = time();
        //判断vip层级是否有vip
        $userVipInfo = $this->getWeixinUserIsvipModel()->newQuery()->where("uid", $data['uid'])->where("lid", $data['lid'])->where("start_time", "<=", $time)->where("end_time", ">=", $time)->first();  //用户是否已是Vip如果是则加上vip
        $vipdata = array();  //将用户月份到vip中去
        $vipdata["uid"] = $data['uid'];
        if (!empty($userVipInfo)) {
            $vipdata["id"] = $userVipInfo->id;
            $endTime = $userVipInfo->end_time; //结束时间
            $endTime = strtotime("+" . $month . " month", $endTime);
            $vipdata["end_time"] = $endTime;
        } else {
            $vipdata["id"] = null;
            $vipdata["start_time"] = $time;
            $vipdata["end_time"] = strtotime("+" . $month . " month", $time);
        }
        $vipdata['lid']=$userInfo->lid;
        //直推返佣金币计算
        if (!empty($userInfo->p1)) {  //直推计算
            $p1Data = array();
            $p1Data["order_sn"] = $shopInfo->id;
            $p1Data["uid"] = $data['uid'];
            $p1Data['mount_type']=2;
            $p1Data["all_mount"] =$shopInfo->amount;
            $bMount=$shopInfo->amount*get_config_param_value("TS_PUSH_DIECT_BACK")/100;
            $p1Data["b_mount"] =number_format($bMount,2) ;
            $p1Data["source_type"] = 1;
            $p1Data["buid"] = $userInfo->p1;
            $p1Data['type'] = 1;
            if(!empty($bMount)){
                $this->getRebateLogInterface()->saveVipData($p1Data);
            }
        }
        //间推返佣金币计算
        if (!empty($userInfo->p2)) {
            $p1Data = array();
            $p1Data["order_sn"] = $shopInfo->id;
            $p1Data["uid"] = $data['uid'];
            $p1Data['mount_type']=2;
            $p1Data["all_mount"] =$shopInfo->amount;
            $bMount=$shopInfo->amount*get_config_param_value("TS_PUSH_DIECT_BACK")/100;
            $p1Data["b_mount"] =number_format($bMount,2) ;
            $p1Data["source_type"] = 2;
            $p1Data["buid"] = $userInfo->p2;
            $p1Data['type'] = 1;
            if(!empty($bMount)){
                $this->getRebateLogInterface()->saveVipData($p1Data);
            }
        }
        $udata = array();
        $udata["vip_pay_times"] = DB::raw("vip_pay_times+1");
        $udata["score_consume"] = DB::raw("score_consume+" . $shopInfo->amount); //消费总金币
        $this->getMemberLevelInterface()->updateData(["id" => $userInfo->lid], $udata);
        //减去用户的金币
        if ($this->getWeixinUserIsvipModel()->newQuery()->updateOrCreate(["id" => $vipdata["id"]], $vipdata)) {
            return $this->getUserInterface()->updateUserScore($data['uid'],-$shopInfo->amount,3,$shopInfo->id,'购买vip消费');  //更新支付状态
        }
    }

    /**
     * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
     * 长度 =2位 + 10位 + 3位 + 3位  = 18位
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @return string
     */
    function makePaySn($member_id)
    {
        return mt_rand(10, 99)
            . sprintf('%010d', time() - 946656000)
            . sprintf('%03d', (float)microtime() * 1000)
            //. sprintf('%03d', (int) $member_id % 1000);
            . $member_id;
    }

    /**
     * 订单编号生成规则，n(n>=1)个订单表对应一个支付表，
     * 生成订单编号(年取1位 + $pay_id取13位 + 第N个子订单取2位)
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @param int $pay_id 支付表自增ID
     * @return string
     */
    function makeOrderSn($pay_id)
    {
        //记录生成子订单的个数，如果生成多个子订单，该值会累加
        static $num;
        if (empty($num)) {
            $num = 1;
        } else {
            $num++;
        }
        return (date('y', time()) % 9 + 1) . $pay_id . sprintf('%01d', $num);
    }


}